package com.study.jyg.rxjava2study.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.study.jyg.rxjava2study.R;
import com.study.jyg.rxjava2study.activity.txplayer.PlayerActivity;
import com.study.jyg.rxjava2study.activity.wifidevicesearch.TestWifiActivity;
import com.study.jyg.rxjava2study.activity.wifidevicesearch.pingwifiip.WifiPingActivity;
import com.study.jyg.rxjava2study.base.BasicActivity;
import com.study.jyg.rxjava2study.richtext.RichTextActivity;
import com.study.jyg.rxjava2study.utils.AdapterInit;
import com.study.jyg.rxjava2study.utils.ExitUtil;
import com.study.jyg.rxjava2study.utils.MsgUtil;
import com.study.jyg.rxjava2study.utils.RxPermissionUtil;
import com.study.jyg.rxjava2study.utils.SystemUtil;
import com.study.jyg.rxjava2study.widget.MyBroadcast;

import java.lang.reflect.Method;
import java.util.Arrays;

import butterknife.BindView;

public class MainActivity extends BasicActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String[] item = {"rxjava", "自定义控件", "获取桌面app包名签名", "WebView", "Dagger2", "通知栏",
            "recyclerview", "RadioGroup", "Tablayout", "游戏", "钉钉打卡", "WIFI中搜索局域网设备",
            "视频播放", "根据pingIP查看局域网可用Ip", "图标颜色根据主题色更改", "身份证", "签名", "蓝牙", "富文本"};
    private BaseQuickAdapter<String, BaseViewHolder> adapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }


    @Override
    protected void initView() {
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());
        MyBroadcast.registerBroadCast(mContext);//注册自定义广播
        initRecyclerView();
//        MsgUtil.getSmsContactList(MainActivity.this);
        SystemUtil.getPhoneNumb(this, strs -> {
            Log.e("mainactivity", "phone = " + strs[0]);
        });
        SystemUtil.getSerialNumber(this, strs -> {
            Log.e("mainactivity", "serial = " + (strs == null ? "null" : strs[0]));
        });
        SystemUtil.getMacAddress(this, strs -> {
            Log.e("mainactivity", "mac = " + strs[0]);
        });
        Log.e("mainactivity", "bluetooth = " + SystemUtil.getBtAddressByReflection()+"");
        Log.e("mainactivity", "battery = " + SystemUtil.getSystemBattery(mContext)+"");
    }


    private void initRecyclerView() {
        adapter = AdapterInit.initRecyclerView(recyclerView, R.layout.item_recyclerview_textview, Arrays.asList(item), new LinearLayoutManager(mContext),
                (helper, item1) -> helper.setText(R.id.tvItem, item1),
                (adapter1, view, position) -> {
                    switch (position) {
                        case 0://rxjava
                            startActivity(RxjavaStudyActivity.class);
                            break;
                        case 1://自定义控件
                            startActivity(CustomControlActivity.class);
                            break;
                        case 2://获取桌面app包名签名
                            startActivity(GetPackageSignActivity.class);
                            break;
                        case 3://WebView
                            startActivity(WebViewActivity.class);
                            break;
                        case 4://Dagger2
                            startActivity(TestDaggerActivity.class);
                            break;
                        case 5://通知栏
                            MyBroadcast.sendBroadCast(mContext);//发送广播
                            break;
                        case 6://recyclerview
                            startActivity(RecyclerViewActivity.class);
                            break;
                        case 7://RadioGroup
                            startActivity(RadioGroupActivity.class);
                            break;
                        case 8://Tablayout
                            startActivity(TabLayoutActivity.class);
                            break;
                        case 9://游戏
                            startActivity(GameActivity.class);
                            break;
                        case 10://钉钉打卡
                            startActivity(DingdingActivity.class);
                            break;
                        case 11://WIFI中搜索局域网设备
//                    startActivity(WifiDeviceSearchActivity.class);
                            startActivity(TestWifiActivity.class);
                            break;
                        case 12://视频播放
                            startActivity(PlayerActivity.class);
                            break;
                        case 13://根据pingIP查看局域网可用Ip
                            startActivity(WifiPingActivity.class);
                            break;
                        case 14://图标颜色根据主题色更改
                            startActivity(IconColourChangeActivity.class);
                            break;
                        case 15://身份证
                            startActivity(IDCardActivity.class);
                            break;
                        case 16://签名
                            startActivity(SignatureActivity.class);
                            break;
                        case 17://蓝牙客户端
                            RxPermissionUtil.initPermission(MainActivity.this, 101, new RxPermissionUtil.RxPermissionListener() {
                                @Override
                                public void isApply() {
                                    startActivity(BluetoothClientActivity.class);
                                }
                            }, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH);
                            break;
                        case 18://富文本
                            startActivity(RichTextActivity.class);
                            break;
                    }
                });
    }

    private final String CHANNEL_ID = "1001";
    private final String CHANNEL_NAME = "ceshi";
    private final int NOTIFY_ID = 1001;

    private void sendNotification() {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//26以上添加了渠道通知
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("通知渠道");
            channel.enableLights(true);
            nm.createNotificationChannel(channel);
        }
        //发送通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        Intent intent = new Intent("com.jyg.study.broadcast.notificationfirst");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, NOTIFY_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("")
                .setContentText("")
                .setAutoCancel(true);
        nm.notify(1, builder.build());

    }

    /**
     * 手动权限申请　如果使用权限类忽略此申请　　（比较老笨的方式需有手动处理回调，看那些参数被禁）
     */
    private void applyPersation() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
    }

    /**
     * 权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
    }


    /**
     * 根据包名关掉应用
     *
     * @param context
     * @param packageName
     */
    private void stopApps(Context context, String packageName) {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            Method forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(am, packageName);
            System.out.println("TimerV force stop package " + packageName + " successful");
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("TimerV force stop package " + packageName + " error!");
        }
    }

    @Override
    public void onBackPressed() {
        ExitUtil.exit(() -> {
            super.onBackPressed();
            com.study.jyg.rxjava2study.utils.ActivityManager.getAppManager().AppExit();
        });
    }
}
